<template>
  <a-card>
    <!-- 搜索表单 -->
    <a-form class="smart-query-form" v-show="showSearch">
      <a-row class="smart-query-form-row">
        <a-form-item label="围栏名称" class="smart-query-form-item">
          <a-input
            v-model:value="queryParams.fenceName"
            placeholder="请输入围栏名称"
            allow-clear
            @press-enter="handleQuery"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <!-- 按钮操作 -->
    <a-row :gutter="10" class="smart-margin-bottom10">
      <a-col :span="1.5">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="default" :disabled="single" @click="handleUpdate">
          <template #icon>
            <EditOutlined />
          </template>
          修改
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button danger :disabled="multiple" @click="handleDelete">
          <template #icon>
            <DeleteOutlined />
          </template>
          删除
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button @click="handleExport">
          <template #icon>
            <DownloadOutlined />
          </template>
          导出
        </a-button>
      </a-col>
    </a-row>

    <!-- 表格显示 -->
    <a-table
      :loading="loading"
      :data-source="fenceInfoList"
      :row-selection="rowSelection"
      :pagination="false"
      row-key="fenceId"
    >
      <a-table-column title="序号" data-index="fenceId" align="center" />
      <a-table-column title="围栏名称" data-index="fenceName" align="center" />
      <a-table-column title="坐标点" data-index="polygonCoords" align="center">
        <template #default="{ record }">
          <span v-if="record.polygonCoords">
            {{ JSON.parse(record.polygonCoords).length }} 个点
          </span>
          <span v-else>-</span>
        </template>
      </a-table-column>
      <a-table-column title="状态" data-index="status" align="center">
        <template #default="{ record }">
          <DictLabel dict-code="sys_normal_disable" :data-value="record.status" />
        </template>
      </a-table-column>
      <a-table-column title="备注" data-index="remark" align="center" />
      <a-table-column title="操作" align="center" :width="150">
        <template #default="{ record }">
          <a-button type="link" @click="handleUpdate(record)">
            <template #icon>
              <EditOutlined />
            </template>
            修改
          </a-button>
          <a-button type="link" danger @click="handleDelete(record)">
            <template #icon>
              <DeleteOutlined />
            </template>
            删除
          </a-button>
        </template>
      </a-table-column>
    </a-table>

    <!-- 分页 -->
    <div class="smart-query-table-page" v-show="total > 0">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="['10', '20', '50', '100']"
        :defaultPageSize="queryParams.pageSize"
        v-model:current="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
        :total="total"
        @change="getList"
        @showSizeChange="getList"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- 添加或修改电子围栏信息对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px" :mask-closable="false">
      <a-form ref="fenceInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="围栏名称" name="fenceName">
          <a-input v-model:value="form.fenceName" placeholder="请输入围栏名称" />
        </a-form-item>
        <a-form-item label="坐标点" name="polygonCoords">
          <a-button @click="openMapDialog">打开地图</a-button>
          <div style="margin-top: 8px; color: #999;">
            {{ form.polygonCoords ? `已绘制 ${JSON.parse(form.polygonCoords).length} 个点` : '尚未绘制围栏' }}
          </div>
        </a-form-item>

        <PolygonMapDialog
          :visible="mapDialogVisible"
          :initialCoords="form.polygonCoords"
          @update:visible="mapDialogVisible = $event"
          @save="handlePolygonSave"
        />
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="form.status">
            <a-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">
              {{ dict.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="form.remark" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" @click="submitForm">确 定</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup>
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue';
  import { listFenceInfo, getFenceInfo, delFenceInfo, addFenceInfo, updateFenceInfo } from "/@/api/offroad/fenceSys/fenceInfo";
  import PolygonMapDialog from "/@/components/PolygonMapDialog.vue";
  import DictLabel from "/@/components/support/dict-label/index.vue";
  import { useDictStore } from '/@/store/modules/system/dict.js';

  const mapDialogVisible = ref(false);
  const openMapDialog = () => {
    mapDialogVisible.value = true;
  };

  const handlePolygonSave = (coords) => {
    form.value.polygonCoords = coords;
    console.log("保存的电子围栏坐标:", coords);
  };

  const { proxy } = getCurrentInstance();
  const dictStore = useDictStore();
  const sys_normal_disable = dictStore.getDictData('sys_normal_disable');

  const fenceInfoList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const selectedRowKeys = ref([]);

  // 行选择配置
  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedKeys, selectedRows) => {
      selectedRowKeys.value = selectedKeys;
      ids.value = selectedKeys;
      single.value = selectedKeys.length !== 1;
      multiple.value = selectedKeys.length === 0;
    }
  };

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      fenceName: null,
    },
    rules: {
      fenceName: [{ required: true, message: "围栏名称不能为空", trigger: "blur" }],
      polygonCoords: [{ required: true, message: "坐标点不能为空", trigger: "blur" }],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询电子围栏信息列表 */
  function getList() {
    loading.value = true;
    listFenceInfo(queryParams.value).then(response => {
      fenceInfoList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      fenceId: null,
      fenceName: null,
      polygonCoords: null,
      status: null,
      remark: null,
      createTime: null,
      updateTime: null
    };
    // 重置表单验证状态
    if (proxy.$refs.fenceInfoRef) {
      proxy.$refs.fenceInfoRef.resetFields();
    }
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      fenceName: null,
    };
    handleQuery();
  }



  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加电子围栏信息";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _fenceId = row.fenceId || ids.value;
    getFenceInfo(_fenceId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改电子围栏信息";
    });
  }

  /** 提交按钮 */
  function submitForm() {
    if (proxy.$refs.fenceInfoRef) {
      proxy.$refs.fenceInfoRef.validate().then(() => {
        if (form.value.fenceId != null) {
          updateFenceInfo(form.value).then(() => {
            message.success("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addFenceInfo(form.value).then(() => {
            message.success("新增成功");
            open.value = false;
            getList();
          });
        }
      }).catch(() => {
        console.log('表单验证失败');
      });
    }
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _fenceIds = row?.fenceId || ids.value;
    Modal.confirm({
      title: '确认删除',
      content: `是否确认删除电子围栏信息编号为"${_fenceIds}"的数据项？`,
      onOk() {
        return delFenceInfo(_fenceIds).then(() => {
          getList();
          message.success("删除成功");
        });
      }
    });
  }

  /** 导出按钮操作 */
  function handleExport() {
    // 这里需要根据实际的导出API进行调整
    console.log('导出功能需要根据实际API实现');
    message.info('导出功能需要根据实际API实现');
  }

  // 初始化数据
  getList();
</script>
